package com.eshop.we.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.eshop.we.admin.entity.Admin;
import com.eshop.we.business.AdminBusiness;
import com.eshop.we.constants.BaseConstants;
import com.eshop.we.result.Result;
import com.eshop.we.utils.CookieUtil;
import com.eshop.we.utils.DesUtil;
import com.eshop.we.utils.MD5Utils;
import com.eshop.we.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/login")
public class AdminController {

    @Autowired
    AdminBusiness adminBusiness;
    @Autowired
    CookieUtil cookieUtil;

    @Autowired
    private RedisUtil redis;

    @PostMapping("/login")
    public Result  login(@RequestParam(required = true)String name, @RequestParam(required = true)String password, HttpServletResponse response)throws Exception{
        password= MD5Utils.encode(password).toLowerCase();
        Admin admin=adminBusiness.selectOne(new EntityWrapper<Admin>().eq("username",name).eq("pwd",password));
        if(admin==null)
        {
            return new Result(BaseConstants.USER_CHECK_ERROR,"用户名或者密码错误！",null);
        }
        String token= DesUtil.getInstance().encrypt(BaseConstants.TOKEN_PREFIX+","+name+","+BaseConstants.TOKEN_SUYFFI);
        String tokenId= MD5Utils.encode(admin.getId()+"eshop"+admin.getCtime());
        redis.set(tokenId,token,60*60*24*30*6);
        cookieUtil.addCookieUser(response,tokenId);
        admin.setToken(token);
        return Result.success(adminBusiness.updateById(admin));
    }

}
